<?php
namespace Ip\Internal\Admin;

class SiteController extends \Ip\Controller
{

    public function login()
    {
        if (\Ip\Internal\Admin\Backend::userId()) {
            //user has already been logged in
            \Ip\Internal\Content\Service::setManagementMode(1);
            return new \Ip\Response\Redirect(ipHomeUrl());
        }

        // If none of the administrator exist, we create default one and log in user
        $administrators = \Ip\Internal\Administrators\Model::getAll();
        if (empty($administrators)) {
            $adminUsername = 'admin';
            $adminEmail = ipGetOptionLang('Config.websiteEmail');
            $adminPassword = Model::randString(8);

            $adminId = \Ip\Internal\Administrators\Service::add($adminUsername, $adminEmail, $adminPassword);
            \Ip\Internal\AdminPermissionsModel::addPermission('Super admin', $adminId);

            // Set variable to know that user is autogenerated
            ipStorage()->set('Ip', 'adminIsAutogenerated', $adminPassword);

            // Logging in new admin
            $model = Model::instance();
            if ($model->login($adminUsername, $adminPassword)) {
                \Ip\Internal\System\Model::sendUsageStatistics(array('action' => 'Install.adminIsAutogenerated'));
                $redirectUrl = ipHomeUrl();
                return new \Ip\Response\Redirect($redirectUrl);
            } else {
                \Ip\Internal\System\Model::sendUsageStatistics(array('action' => 'Install.adminIsAutogeneratedFailed'));
                // todo: handle errors
                // $errors = $model->getErrors();
            }
        }

        $content = ipView('view/login.php', array('loginForm' => FormHelper::getLoginForm()));
        ipAddJs('Ip/Internal/Admin/assets/login.js');
        $response = ipResponse();
        $response->setLayout('Ip/Internal/Admin/view/loginLayout.php');
        $response->setLayoutVariable('content', $content);
        ipAddJs('assets/languageSelect.js');
        $response->setLayoutVariable('languageSelectForm', FormHelper::getLanguageSelectForm());

        return $response;
    }

    public function passwordResetForm()
    {
        if (\Ip\Internal\Admin\Backend::userId()) {
            //user has already been logged in
            \Ip\Internal\Content\Service::setManagementMode(1);
            return new \Ip\Response\Redirect(ipHomeUrl());
        }


        $content = ipView('view/passwordReset.php', array('passwordResetForm' => FormHelper::getPasswordResetForm1()));
        ipAddJs('Ip/Internal/Admin/assets/passwordReset1.js');

        $response = ipResponse();
        $response->setLayout('Ip/Internal/Admin/view/loginLayout.php');
        $response->setLayoutVariable('content', $content);
        ipAddJs('assets/languageSelect.js');
        $response->setLayoutVariable('languageSelectForm', FormHelper::getLanguageSelectForm());


        return $response;

    }

    public function passwordResetInfo()
    {
        if (\Ip\Internal\Admin\Backend::userId()) {
            //user has already been logged in
            \Ip\Internal\Content\Service::setManagementMode(1);
            return new \Ip\Response\Redirect(ipHomeUrl());
        }


        $content = ipView('view/passwordResetInfo.php');

        $response = ipResponse();
        $response->setLayout('Ip/Internal/Admin/view/loginLayout.php');
        $response->setLayoutVariable('content', $content);
        ipAddJs('assets/languageSelect.js');
        $response->setLayoutVariable('languageSelectForm', FormHelper::getLanguageSelectForm());


        return $response;

    }

    public function passwordResetSuccess()
    {
        if (\Ip\Internal\Admin\Backend::userId()) {
            //user has already been logged in
            \Ip\Internal\Content\Service::setManagementMode(1);
            return new \Ip\Response\Redirect(ipHomeUrl());
        }


        $content = ipView('view/passwordResetSuccess.php');

        $response = ipResponse();
        $response->setLayout('Ip/Internal/Admin/view/loginLayout.php');
        $response->setLayoutVariable('content', $content);
        ipAddJs('assets/languageSelect.js');
        $response->setLayoutVariable('languageSelectForm', FormHelper::getLanguageSelectForm());


        return $response;

    }

    public function passwordReset()
    {
        if (\Ip\Internal\Admin\Backend::userId()) {
            //user has already been logged in
            \Ip\Internal\Content\Service::setManagementMode(1);
            return new \Ip\Response\Redirect(ipHomeUrl());
        }


        $content = ipView('view/passwordReset2.php', array('passwordResetForm' => FormHelper::getPasswordResetForm2()));
        ipAddJs('Ip/Internal/Admin/assets/passwordReset2.js');

        $response = ipResponse();
        $response->setLayout('Ip/Internal/Admin/view/loginLayout.php');
        $response->setLayoutVariable('content', $content);
        ipAddJs('assets/languageSelect.js');
        $response->setLayoutVariable('languageSelectForm', FormHelper::getLanguageSelectForm());


        return $response;
    }

    public function loginAjax()
    {

        ipRequest()->mustBePost();

        $validateForm = FormHelper::getLoginForm();
        $errors = $validateForm->validate(ipRequest()->getPost());

        $username = ipRequest()->getPost('login');

        if (empty($errors)) {
            $model = Model::instance();
            if (!$model->login($username, ipRequest()->getPost('password'))) {
                $errors = $model->getErrors();
            }
        }

        $redirectUrl = ipHomeUrl();

        $model = Model::instance();
        $adminMenuItems = $model->getAdminMenuItems(null);
        if (!empty($adminMenuItems)) {
            //redirect user to the first module
            $firstMenuItem = $adminMenuItems[0];
            $redirectUrl = $firstMenuItem->getUrl();
        }

        if (empty($errors)) {
            $answer = array(
                'status' => 'success',
                'redirectUrl' => $redirectUrl
            );
        } else {
            $answer = array(
                'status' => 'error',
                'errors' => $errors
            );
            $usageStatistics = array(
                'action' => 'Admin.loginFailed',
                'data' => array(
                    'admin' => $username,
                    'errors' => $errors
                )
            );
            \Ip\Internal\System\Model::sendUsageStatistics($usageStatistics);
        }

        if (ipRequest()->getPost('ajax', 1)) {
            $response = new \Ip\Response\Json($answer);
            return $response;
        } else {
            //MultiSite autologin
            return new \Ip\Response\Redirect($redirectUrl);
        }
    }

    public function passwordResetAjax()
    {

        ipRequest()->mustBePost();

        $validateForm = FormHelper::getPasswordResetForm1();
        $errors = $validateForm->validate(ipRequest()->getPost());

        $username = ipRequest()->getPost('username');

        if (empty($errors)) {
            $user = \Ip\Internal\Administrators\Service::getByEmail($username);
            if (!$user) {
                $user = \Ip\Internal\Administrators\Service::getByUsername($username);
            }

            if ($user) {
                \Ip\Internal\Administrators\Service::sendResetPasswordLink($user['id']);
            } else {
                $errors['username'] = __('Following administrator doesn\'t exist', 'Ip-admin', false);
            }

        }

        if (empty($errors)) {
            $answer = array(
                'status' => 'success',
                'redirectUrl' => ipActionUrl(array('sa' => 'Admin.passwordResetInfo'))
            );
        } else {
            $answer = array(
                'status' => 'error',
                'errors' => $errors
            );
        }

        $response = new \Ip\Response\Json($answer);
        return $response;
    }

    public function passwordResetAjax2()
    {

        ipRequest()->mustBePost();

        $validateForm = FormHelper::getPasswordResetForm2();
        $errors = $validateForm->validate(ipRequest()->getPost());

        $userId = ipRequest()->getPost('userId');
        $secret = ipRequest()->getPost('secret');
        $password = ipRequest()->getPost('password');


        try {
            \Ip\Internal\Administrators\Service::resetPassword($userId, $secret, $password);
        } catch (\Ip\Exception $e) {
            $user['global_error'] = $e->getMessage();
        }


        if (empty($errors)) {
            $answer = array(
                'status' => 'success',
                'redirectUrl' => ipActionUrl(array('sa' => 'Admin.passwordResetSuccess'))
            );
        } else {
            $answer = array(
                'status' => 'error',
                'errors' => $errors
            );
        }

        $response = new \Ip\Response\Json($answer);
        return $response;
    }

    public function logout()
    {
        Model::instance()->logout();
        return new \Ip\Response\Redirect(ipFileUrl('admin/'));
    }

    public function sessionRefresh()
    {
        return new \Ip\Response\Json(array());
    }


    public function changeLanguage()
    {
        $locale = ipRequest()->getPost('languageCode', 'en');
        $hour = 60 * 60;
        $day = $hour * 24;
        setcookie("ipAdminLocale", $locale, time() + $day * ipGetOption('Config.adminLocaleCookieExpire', 10 * 365));
        return new \Ip\Response\Json(array('success' => 1));
    }


}
